﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using Wicture.DbRESTFul.SQL;
using Wicture.EPC.Common;
using Wicture.EPC.Service.V1.Models;
using Wicture.EPC.Service.V1.Repository;
using Wicture.EPC.Service.V1.Resources;

namespace Wicture.EPC.Service.V1.QueryInterceptors.Interceptors
{
    public class SgmQueryInterceptor : BaseQueryInterceptor
    {
        private readonly string[] brandCodes = new string[] { "buick", "chevrolet", "cadillac" };

        public override string[] BrandCodes => brandCodes;

        public override object QueryHotPoints(DbRESTFulRepository repository, JObject param)
        {
            IEnumerable<dynamic> data = repository.Invoke(CSIs.Query_HotPoints_For_Sgm, param);
            if (data.Count() == 0) return null;
            return new
            {
                imgs = new List<Query_HotPointsResult._imgs> {
                    new Query_HotPointsResult._imgs {
                        url =data.FirstOrDefault().url,
                        points =JArray.FromObject(data).ToObject<List<Query_HotPointsResult._imgs._points>>()
                    }
                }
            };
        }

        public override object QueryParts(DbRESTFulRepository repository, JObject param)
        {
            param.RemoveEmptyValues();
            string selectorId = param.Value<string>(ParamFields._selectorId);
            List<Query_PartsResult> result = repository.Invoke<Query_PartsResult>(CSIs.Query_Parts_For_Sgm, param);
            foreach (var item in result)
            {
                if (!string.IsNullOrEmpty(item.description))
                {
                    item.modelNotes += $"$${item.description}";
                    item.description = "";
                }
                if (!string.IsNullOrEmpty(item.hand))
                {
                    item.modelNotes += $"$$左右:{item.hand}";
                    item.hand = "";
                }

                if (item.firstYear.HasValue || item.lastYear.HasValue)
                {
                    item.modelNotes += $"$$年份:{item.firstYear} - {item.lastYear}";
                }

                if (item.modelNotes != null && item.modelNotes.StartsWith("$$"))
                {
                    item.modelNotes = item.modelNotes.Substring(2);
                }

                if (!string.IsNullOrEmpty(item.modelFilter))
                {
                    item.notes += $"$$正选装";
                    var features = item.modelFilter.Split(',');
                    foreach (var feature in features)
                    {
                        item.notes += $"$${feature}:";
                        if (ResourceHelper.SgmFeatureDict.ContainsKey(feature))
                        {
                            item.notes += $"{ResourceHelper.SgmFeatureDict[feature]}";
                        }
                    }
                    item.modelFilter = "";
                }
                if (!string.IsNullOrEmpty(item.featureCodes))
                {
                    item.notes += $"$$负选装";
                    var features = item.featureCodes.Split(',');
                    foreach (var feature in features)
                    {
                        item.notes += $"$${feature}:";
                        if (ResourceHelper.SgmFeatureDict.ContainsKey(feature))
                        {
                            item.notes += $"{ResourceHelper.SgmFeatureDict[feature]}";
                        }
                    }
                    item.featureCodes = "";
                }
                if (!string.IsNullOrEmpty(item.series))
                {
                    item.notes += $"$$车系:{item.series}";
                    item.series = "";
                }
                if (!string.IsNullOrEmpty(item.bodyColor))
                {
                    item.notes += $"$$车身:{item.bodyColor}";
                    item.bodyColor = "";
                }
                if (item.notes != null && item.notes.StartsWith("$$"))
                {
                    item.notes = item.notes.Substring(2);
                }

            }
            return result;
        }

        public override object QueryPartDetail(DbRESTFulRepository repository, JObject param)
        {
            param.RemoveEmptyValues();
            var brandCode = param.Value<string>(ParamFields._brandCode);
            var partId = param.Value<string>(ParamFields._partId);
            dynamic data = null;
            if (string.IsNullOrEmpty(partId))
            {
                data = repository.Invoke(CSIs.Get_Part_Detail_For_Sgm, param);
            }
            else
            {
                data = repository.Invoke(CSIs.Get_Usage_Detail_For_Sgm, param);
            }
            if (data == null) return null;
            // 1、基本信息赋值
            Query_Part_DetailResult result = JObject.FromObject(data).ToObject<Query_Part_DetailResult>();

            result.replacements = new List<Query_Part_DetailResult._replacement>();
            //3.替换件处理
            if (!string.IsNullOrEmpty(data.replacementPartNo))
            {
                List<Query_Part_DetailResult._replacement> replacements = repository.Invoke<Query_Part_DetailResult._replacement>(CSIs.Query_Parts_By_Codes, new { partCodes = data.replacementPartNo.Split(',') });
                if (replacements != null)
                {
                    foreach (var replacement in replacements)
                    {
                        replacement.brandCode = brandCode;
                        replacement.brandName = BrandDictionary.GetName(brandCode);
                        if (replacement.disabled.HasValue)
                        {
                            replacement.props = new List<Query_Part_DetailResult._prop>();
                            replacement.props.Add(new Query_Part_DetailResult._prop { key = "是否禁用", value = replacement.disabled.HasValue ? (replacement.disabled.Value ? "是" : "否") : "" });
                        }
                        result.replacements.Add(replacement);
                    }
                }
            }

            //4.配件附加属性处理
            var props = new List<Query_Part_DetailResult._prop>
            {
                new Query_Part_DetailResult._prop { key = "件数", value = result.quantity ?? string.Empty },
                new Query_Part_DetailResult._prop { key = "备注", value = result.remark ?? string.Empty },
                new Query_Part_DetailResult._prop { key = "左右", value = data.hand?.ToString() },
                new Query_Part_DetailResult._prop { key = "车身", value = data.body?.ToString() },
                new Query_Part_DetailResult._prop { key = "车系", value = data.series?.ToString() },
                new Query_Part_DetailResult._prop { key = "正选装", value = data.optionP?.ToString() },
                new Query_Part_DetailResult._prop { key = "负选装", value = data.optionN?.ToString() },
                new Query_Part_DetailResult._prop { key = "最小包装数", value = data.minQuantity?.ToString() },
                new Query_Part_DetailResult._prop { key = "是否禁用", value = result.disabled.HasValue ?(result.disabled.Value?"是":"否"):"否" }
            };
            result.props = props.Where(q => !string.IsNullOrEmpty(q.value)).ToList();
            return result;
        }

        protected override dynamic GetModelsByPart(DbRESTFulRepository repository, int pageIndex, int pageSize, string brandCode, string partCode)
        {
            return repository.Invoke(CSIs.Query_Models_By_Part_For_Sgm, new { pageIndex, pageSize, brandCode, partCode });
        }

        protected override dynamic GetHotPointsByPart(DbRESTFulRepository repository, string brandCode, string partCode, IEnumerable<string> imageIds)
        {
            return repository.Invoke(CSIs.Query_HotPoints_By_Part_For_Sgm, new { brandCode, partCode, imageIds });
        }

        protected override List<Query_SubGroupResult> FilterSubGroupsByVin(DbRESTFulRepository repository, List<Query_SubGroupResult> results, JObject param)
        {
            var vin = param.Value<string>(ParamFields._vin);
            return results;
        }
        protected override void FilterPartsByVin(DbRESTFulRepository repository, ref List<Query_PartsResult> result, string vin, string selectorId)
        {
        }

        protected override List<QuickPartResult> QuickQueryPartsFilterByUsage_Vin(DbRESTFulRepository repository, List<QuickPartResult> parts, int selectorId, string vin)
        {
            return base.QuickQueryPartsFilterByUsage_Model(repository, parts, selectorId);
        }
    }
}



